/**
 * Created by Amit Mudgal (Principal Consultant - MicroStrategy)
 * Project Team : GCST (Travel)
 * Creation date : 03/06/2014
 *
 */

package com.amex.SQL;

import java.sql.Connection;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ResourceBundle;
import com.microstrategy.web.beans.MarkupOutput;
import com.microstrategy.web.beans.RequestKeys;
import com.microstrategy.web.objects.WebIServerSession;
import com.microstrategy.web.objects.WebObjectsFactory;
import com.microstrategy.web.tasks.AbstractBaseTask;
import com.microstrategy.web.tasks.Task;
import com.microstrategy.web.tasks.TaskRequestContext;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.json.JsonHierarchicalStreamDriver;
import com.amex.Crypto.Encryption;
import com.amex.SQL.DBOperations;

public class GetReportList extends AbstractBaseTask implements Task   {
	private static final String PROPERTIES_FILE_NAME = "DBConnection";
	private static final String DB_HOSTNAME = "DB_HOSTNAME_HL";
	private static final String DB_NAME = "DB_NAME_HL";
	private static final String DB_USER_ID = "DB_USER_ID_HL";
	private static final String DB_EPWD = "DB_EPWD_HL";
	
	private static String HL_HOSTNAME; 
	private static String HL_DB_NAME;
	private static String HL_USER_ID;
	private static String HL_EPWD;
	private static String HL_MSGINFO_SQL = "select MESSAGE_ID, SUBINST_ID, OBJECT_ID,PROJECT_NAME,OBJECT_NAME,OBJECT_DESC,START_TIME,FINISH_TIME," +
			                               "REQUEST_STATUS,CREATION_TIME,MODIFICATION_TIME,MESSAGE_TEXT,MESSAGE_OWNER_NAME from DSSCSMSGINFO where" +
			                               " MESSAGE_OWNER_NAME = '";
	
	static {
        ResourceBundle props = ResourceBundle.getBundle(PROPERTIES_FILE_NAME);
        HL_HOSTNAME = (String) props.getObject(DB_HOSTNAME);
        HL_DB_NAME = (String) props.getObject(DB_NAME);
        HL_USER_ID = (String) props.getObject(DB_USER_ID);
        HL_EPWD = (String) props.getObject(DB_EPWD);
	}
	
	
    public GetReportList() {
        super("This task gives the History list for a user for all projects user has access over. This translates to users Report list");
    }

    public void processRequest(TaskRequestContext context, MarkupOutput out) {
    	Map<String, HistoryListLineItems> reportList = new HashMap<String, HistoryListLineItems>();	
    	List<HistoryListLineItems> jbList = new ArrayList<HistoryListLineItems>();	
    	RequestKeys keys = context.getRequestKeys();
    	String sessionState = keys.getValue("session");
    	try{
    		WebObjectsFactory factory=WebObjectsFactory.getInstance();
    		WebIServerSession iSession = factory.getIServerSession();
    		iSession.restoreState(sessionState);
    		String userName = iSession.getUserInfo().getName();
    		String SQLHL = HL_MSGINFO_SQL + userName + "'";
    		Connection conn = DBOperations.SQLconnect(HL_HOSTNAME, HL_DB_NAME, HL_USER_ID, Encryption.Decrypt(HL_EPWD));
    		ResultSet rs = DBOperations.ExecSQLQuery(conn, SQLHL);
    		String json = "";
    		while(rs.next()){
    			HistoryListLineItems rpt = getReport(rs.getString("OBJECT_ID"), reportList);
    			Map<String, String> reportEntity = new HashMap<String, String>();
    			reportEntity.put("MESSAGE_ID", rs.getString("MESSAGE_ID"));
    			reportEntity.put("SUBINST_ID", rs.getString("SUBINST_ID"));
    			reportEntity.put("OBJECT_ID", rs.getString("OBJECT_ID"));
    			reportEntity.put("PROJECT_NAME", rs.getString("PROJECT_NAME"));
    			reportEntity.put("OBJECT_NAME", rs.getString("OBJECT_NAME"));
    			reportEntity.put("OBJECT_DESC", rs.getString("OBJECT_DESC"));
    			reportEntity.put("START_TIME", rs.getString("START_TIME"));
    			reportEntity.put("FINISH_TIME", rs.getString("FINISH_TIME"));
    			reportEntity.put("REQUEST_STATUS", rs.getString("REQUEST_STATUS"));
    			reportEntity.put("CREATION_TIME", rs.getString("CREATION_TIME"));
    			reportEntity.put("MODIFICATION_TIME", rs.getString("MODIFICATION_TIME"));
    			reportEntity.put("MESSAGE_OWNER_NAME", rs.getString("MESSAGE_OWNER_NAME"));
    			setReport(reportEntity, rpt);
    		}
    		int h = 0;
    		HistoryListLineItems hls[] = new HistoryListLineItems[reportList.size()];
    		for(String key : reportList.keySet()){
    			HistoryListLineItems hl = reportList.get(key);
    			hls[h] = hl;
    			h++;
    		}
    		System.out.println(reportList.size());
    		XStream xstream = new XStream(new JsonHierarchicalStreamDriver()); 
    		xstream.alias("report", HistoryListLineItems.class); 
    		xstream.alias("message", HistoryListSubItems.class); 
    		json = xstream.toXML(hls);
    		System.out.println(json);
    		out.append(json);
    		DBOperations.SQLDisconnect(conn);
    	  
        }catch(Exception e){System.out.println("Error Occured in getting project List" +e);}
    }
    /** 
     * Creates a report factory
     * @param reportID String
     * @return report Map
     */
    public HistoryListLineItems getReport(String objectID, Map<String, HistoryListLineItems> reportList){
    	HistoryListLineItems report = reportList.get(objectID);
    	if(report==null){
    		report = new HistoryListLineItems();
    		reportList.put(objectID, report);
    	}
    	return report;
    }
    
    /** 
     * set report value
     * @param rsMap(the rsMap data is from ResultSet) Map<String, String>
     * @param report Map<String, Object> report)
     */
    public void setReport(Map<String, String> rsMap, HistoryListLineItems rpt){
    	if(rpt.getObjID()==null || rpt.getObjID().equals("")){
    		String rptID = rsMap.get("OBJECT_ID");//put rs data into rsMap
    		rpt.setObjID(rptID);
    		rpt.setObjName(rsMap.get("OBJECT_NAME"));
    		//rpt.setlistOfSubInstID(rsMap.get("SUBINST_ID"));
    		//rpt.setlistOfProjectNames(rsMap.get("PROJECT_NAME"));
    		rpt.setObjDesc(rsMap.get("OBJECT_DESC"));
    		//rpt.setlistOfStartTimes(rsMap.get("START_TIME"));
    		//rpt.setlistOfFinishTimes(rsMap.get("FINISH_TIME"));
    		rpt.setReqStatus(rsMap.get("REQUEST_STATUS"));
    		//rpt.setlistOfCreationTimes(rsMap.get("CREATION_TIME"));
    		rpt.setmTime(rsMap.get("MODIFICATION_TIME"));
    	}
    	List<HistoryListSubItems> subHLItems = rpt.getSubHLItems();
    	if(subHLItems==null){
    		subHLItems = new ArrayList<HistoryListSubItems>();
    		rpt.setSubHLItems(subHLItems);
    	}
    	HistoryListSubItems hlSubItems = new HistoryListSubItems();
    	hlSubItems.setSubMesgID(rsMap.get("MESSAGE_ID"));
    	//hlSubItems.setSubObjID(rsMap.get("OBJECT_ID"));
    	//hlSubItems.setObjName(rsMap.get("OBJECT_NAME"));
    	//hlSubItems.setPrjName(rsMap.get("PROJECT_NAME"));
    	//hlSubItems.setObjDesc(rsMap.get("OBJECT_DESC"));
    	hlSubItems.setModificationTime(rsMap.get("MODIFICATION_TIME"));
    	//hlSubItems.setMesgOwnerName(rsMap.get("MESSAGE_OWNER_NAME"));
    	subHLItems.add(hlSubItems);
    }
}